using MediatR;
using RBAC.Domain.WarehouseManagement;
using RBAC.ErrorCode;
using RBAC.Read.Api.Application.Command.ERP.LoggingTables;
using RBAC.Interstructrue.Base;
using Dapper;
using RBAC.Read.Api.Application.Dto.ERP.LoggingTables;
using System.Linq;

namespace RBAC.Read.Api.Application.Handler.ERP.LoggingTables
{
    public class GetLoggingCommandHandler : IRequestHandler<GetLoggingCommands, APIResult<APIPaging<LoggingTable>>>
    {
        private readonly IBaseRepository<LoggingTableRecord> _loggingRepo;

        public GetLoggingCommandHandler(IBaseRepository<LoggingTableRecord> loggingRepo)
        {
            _loggingRepo = loggingRepo;
        }

        public async Task<APIResult<APIPaging<LoggingTable>>> Handle(GetLoggingCommands request, CancellationToken cancellationToken)
        {
            // 允许PageIndex/PageSize默认值
            var pageIndex = request.PageIndex <= 0 ? 1 : request.PageIndex;
            var pageSize = request.PageSize <= 0 ? 10 : request.PageSize;

            // 目前无额外查询条件，如后续需要可在命令中增加筛选字段
            var whereClause = string.Empty;
            var parameters = new DynamicParameters();

            var (data, totalCount) = _loggingRepo.GetPaged(
                pageIndex,
                pageSize,
                whereClause,
                "CreateTime DESC",
                parameters
            );

            // DTO -> 原实体映射（保持对外返回不变）
            var viewData = data.Select(x => new LoggingTable
            {
                LoggingId = x.LoggingId,
                UserId = x.UserId,
                UserName = x.UserName,
                OperationContent = x.OperationContent,
                CreateTime = x.CreateTime,
                IsDeleted = x.IsDeleted
            }).ToList();

            var result = new APIResult<APIPaging<LoggingTable>>
            {
                Code = APIEnums.Success,
                Msg = "查询成功",
                Data = new APIPaging<LoggingTable>
                {
                    TotalCount = totalCount,
                    PageDatas = viewData
                }
            };

            return await Task.FromResult(result);
        }
    }
}
